$(document).ready(function() {
	
	//need this to do polling
	var timeout;
	
	$('.open-login-lightbox').click(function(){
		$('#lightbox').slideToggle('slow', function() {
		});
	});
	$('#drop-down-countries').click(function() {
		$('#drop-down-countries-list').slideToggle('slow', function() {
		});
	});
	$('#drop-down-regions').click(function() {
		$('#drop-down-regions-list').slideToggle('slow', function() {
		});
	});
	$('#drop-down-places').click(function() {
		$('#drop-down-places-list').slideToggle('slow', function() {
		});
	});
	$('.listed_country').click(function() {
		var selected_country_id = $(this).children('.listed_country_id').text();
		var selected_country_name = $(this).children('.listed_country_name').text();
		$('#add-new-place-information-container').slideUp();
		$('#drop-down-countries').html(selected_country_name);
		$('#chosen-country-id').html(selected_country_id);
		$('#drop-down-countries-list').slideUp('slow');
		//If selecting countries all over again
		$('#drop-down-places').slideUp();
		$('#drop-down-regions').slideUp();
		$('#drop-down-regions').html("Select a region");
		$('#drop-down-places').html("Select a place");
		$('#add_new_place').fadeOut();
		$('#add_new_place_form_container').fadeOut();
		
		$.ajax({
			type:'POST',
			url:'get_regions.php',
			data:'country_id='+selected_country_id,
			dataType: 'json',
			error: function(request, status, error) {
				 alert(request.responseText);
			},
			beforeSend: function() {
				//Before posting region, close slider and empty it.
				$("#drop-down-regions-list").slideUp();
				$("#drop-down-regions-list").empty();
			},
			success: function(response) {
				for(i=0; i<=response.length-1; i++) {
					$("#drop-down-regions-list").append("<span class='listed_region'><span class='listed_region_name'>" + response[i]["name"] + "</span><span class='listed_region_id'>" + response[i]["id"] + "</span></span><br>");
				}
			},
			complete: function (response) {
				//open the slider with the regions and instructions
				$('#drop-down-regions-list').slideDown('slow');
				$('#drop-down-regions').html("Select a Region");
				$('#drop-down-regions').slideDown('slow');
			}
		});
	});
	//var isFound = false;
	$('#name-of-new-place').keydown(function (e){
		if(e.keyCode == 13) {
			var address = $('#name-of-new-place').val();
			check_location_exists(address);
			$('#add-new-place-information-container').slideUp(function() {
				$('#add-new-place-name-container').html($('#name-of-new-place').val());
			});
			$('#comment-container').slideUp();
			$('#place_information_container').slideUp();
			$('#add-new-place-information-container').slideDown();
		}
	});
	
	$('#button-add-holder').click(function(){
		var region_id = $('#chosen-region-id').text();
		var place_lat = $('#place-lat').text();
		var place_long = $('#place-long').text();
		var name = $('#add-new-place-name-container').text();
		$.ajax({
			type:'POST',
			url:'add_place.php',
			data:"name="+name+"&id="+region_id+"&lat="+place_lat+"&long="+place_long,
			error: function(request, status, error) {
				 alert(request.responseText);
			},
			success:function(response){
				if(response == 0) {
					error_report("Error Adding Place", "The place you are trying to add already exists");
				} else {
					$("#drop-down-places-list").slideUp();
					$("#drop-down-places-list").append("<span class='listed_place'><span class='listed_place_name'>" + name + "</span><span class='listed_place_id'>" + response + "</span></span><br>");
					$("#drop-down-places-list").slideDown();
					$("#drop-down-place").slideDown();
				}
			}
		});
		$('#add-new-place-information-container').slideUp();
	});
	
	$('#admin-add-region-field').keydown(function (e){
		if(e.keyCode == 13) {
			var address = $('#admin-add-region-field').val() + ', ' + $('#admin-add-country-field').val();
			var result = add_country_region(address);
			$('#admin-add-country-region-container').fadeIn();
			$('#admin-add-country-region-name').empty();
			$('#admin-add-country-region-name').append($('#admin-add-country-field').val() + ', ' + $('#admin-add-region-field').val())
		}
	});
	
	$('#admin-add-country-field').keydown(function (e){
		if(e.keyCode == 13) {
			var address = $('#admin-add-country-field').val();
			var result = add_country_region(address);
			$('#admin-add-country-region-container').fadeIn();
			$('#admin-add-country-region-name').empty();
			$('#admin-add-country-region-name').append($('#admin-add-country-field').val());
		}
	});
	$('#admin-add-country-region-confirm').on('click', function() {
		if(!$('#admin-add-region-field').val()) {
			var address = $('#admin-add-country-field').val();
			$.ajax({
				type:'POST',
				url:'add_country.php',
				data:"name="+address,
				error: function(request, status, error) {
					 alert(request.responseText);
				},
				success:function(response){
					if(response == 0) {
						error_report("Error Adding Country", "The country you are trying to add already exists.");
					} else {
						error_report("Country Successfully Added", "This country is now available to add regions.");
					}
				}
			});
		} else {
			var country = $('#admin-add-country-field').val();
			var region = $('#admin-add-region-field').val();
			var lat = $('#admin-lat').text();
			var llong = $('#admin-long').text();
			//alert(country);
			//alert(region);
			$.ajax({
				type:'POST',
				url:'add_region.php',
				data:"country="+country+"&region="+region+"&lat="+lat+"&long="+llong,
				error: function(request, status, error) {
					 alert(request.responseText);
				},
				success:function(response){
					if(response == 0) {
						error_report("Error Adding Region", "The region you are trying to add already exists.");
					} else if(response == -1) {
						error_report("Error Adding Region", "The country you are trying to add this region to does not exist. Please create that country first.");
					} else {
						error_report("Region Successfully Added", "This region is now available to add places.");
					}
				}
			});
		}
	});
	$("#username").focus(function () {
		$("#username").keyup(function() {
			if($('#username').val().length <= 0) {
				$('#username-error-message').empty();
			} else if($('#username').val().length <= 2) {
				$('#username-error-message').html("Username must be 3 to 16 characters.");
			} else if($('#username').val().length >= 17) {
				$('#username-error-message').html("Username must be 3 to 16 characters.");
			} else {
				$('#username-error-message').empty();
			}
		});
	});
	$("#password").focus(function () {
		$("#password").keyup(function() {
			if($('#password').val().length <= 0) {
				$('#password1-error-message').empty();
			} else if($('#password').val().length <= 5) {
				$('#password1-error-message').html("Password must be 6 to 12 characters.");
			} else if($('#password').val().length >= 13) {
				$('#password1-error-message').html("Password must be 6 to 12 characters.");
			} else {
				$('#password1-error-message').empty();
			}
		});
	});
	$("#password2").focus(function () {
		$("#password2").keyup(function() {
		//$('#password2-error-message').html($('#password2').val().length);
			if($('#password2').val().length == 0) {
				$('#password2-error-message').html("Please repeat password");
			} else if($('#password2').val().length != $('#password').val().length) {
				$('#password2-error-message').html("Password Mismatch");
			} else if($('#password2').val() != $('#password').val()) {
				$('#password2-error-message').html("Password Mismatch");
			} else if($('#password2').val() == $('#password').val()) {
				$('#password2-error-message').html("Passwords Matched");
			}
		});
	});
});

function check_location_exists(address) {
	var geo = new google.maps.Geocoder;
	var region = $('#drop-down-regions').text();
	var country = $('#drop-down-countries').text();
	geo.geocode({'address': address + ", " + region + ", " + country}, function(results, status) {
		if(status == google.maps.GeocoderStatus.OK) {
			var latitude = results[0].geometry.location.lat();
			var longitude = results[0].geometry.location.lng();
			$('#place-lat').empty();
			$('#place-lat').html(latitude);
			$('#place-long').empty();
			$('#place-long').html(longitude);
			addPlaceMarker(latitude, longitude);
			return "1";
		} else {
			return "2";
		}
	});
}

function add_country_region(address) {
	var geo = new google.maps.Geocoder;
	geo.geocode({'address': address}, function(results, status) {
		if(status == google.maps.GeocoderStatus.OK) {
			var latitude = results[0].geometry.location.lat();
			var longitude = results[0].geometry.location.lng();
			addPlaceMarker(latitude, longitude);
			$('#admin-lat').html(latitude);
			$('#admin-long').html(longitude);
			return results;
		} else {
			return "2";
		}
	});
}

$(document).on('click', '.listed_region',function() {
	var selected_region_id = $(this).children('.listed_region_id').text();
	var selected_region_name = $(this).children('.listed_region_name').text();
	
	$('#add-new-place-information-container').slideUp();
	$('#drop-down-regions-list').slideUp('slow');
	$('#drop-down-regions').html(selected_region_name);
	$('#chosen-region-id').html(selected_region_id);
	//If reselecting region, close all places
	$('#drop-down-regions').slideDown();
	$('#drop-down-places').slideUp();
	$('#drop-down-places').html("Select a place");
	
	$.ajax({
		type:'POST',
		url:'get_places.php',
		data:'region_id='+selected_region_id,
		dataType: 'json',
		error: function(request, status, error) {
			 alert(request.responseText);
		},
		beforeSend: function() {
			$("#drop-down-places-list").slideUp();
			$("#drop-down-places-list").empty();
		},
		success: function(response) {
			for(i=0; i<=response.length-1; i++) {
				$("#drop-down-places-list").append("<span class='listed_place'><span class='listed_place_name'>" + response[i]["name"] + "</span><span class='listed_place_id'>" + response[i]["id"] + "</span></span><br>");
			}
		},
		complete: function (response) {
			//add new place, also add new region etc
			$('#drop-down-places-list').slideDown('slow');
			$('#drop-down-places').slideDown('slow');
		}
	});
	$('#add_new_place').fadeIn();
});

$(document).on('click', '.listed_place',function() {
	var selected_place_id = $(this).children('.listed_place_id').text();
	var selected_place_name = $(this).children('.listed_place_name').text();

	$('#add-new-place-information-container').slideUp();
	$('#drop-down-places').slideDown();
	$('#explore_place_name').empty();
	$('#explore_place_name').append(selected_place_name);
	$('#drop-down-places').html(selected_place_name + '<span id="final-selection-id">' + selected_place_id + '</span>');
	//$('#place-photo-line-up').html("<img class='place-photos' id='add-place-photo-button' src='images/add-photo-default.png'>");
	$('#drop-down-places-list').slideUp('slow', function() {
	});
	$.ajax({
		type:'POST',
		url:'get_place_vote.php',
		data:'place_id='+selected_place_id,
		error: function(request, status, error) {
			alert(request.responseText);
		},
		success: function(response) {
			if(response == '') {
				$('#place_vote_count').html('0');
			} else {
				$('#place_vote_count').html(response);
			}
		},
	});
	/*
	Use this to pull pictures for the place. Use JSON
	*/
	$.ajax({
		type:'POST',
		url:'get_place_photos.php',
		data:'place_id='+selected_place_id,
		dataType: 'json',
		error: function(request, status, error) {
			alert(request.responseText);
		},
		success: function(response) {
			$('#user-added-photos').empty();
			if(response != 0) {
				for(i = 0; i <= response.length-1; i++) {
					//append img
					$('#user-added-photos').append("<img class='place-photos' src='images/places/" + response[i] + "'>");
				}
			}
			$('#view-all-place-photos a').attr('href', 'gallery.php?place_id=' + selected_place_id);
		},
	});
	
	$('#place_information_container').slideDown();
	$.ajax({
		type:'POST',
		url:'get_place_information.php',
		data:'place_id='+selected_place_id,
		dataType: 'json',
		error: function(request, status, error) {
			 alert(request.responseText);
		},
		beforeSend: function() {
			$('#comment-box').slideUp();
			$('#comment-box').fadeOut('slow');
			$('#comment-box').empty();
		},
		success: function(response) {
			addPlaceMarker(response[1][0]["lat"], response[1][0]["long"]);
			if(response[0] == 2) {
				$('#comment-box').append("<div id='empty-comments'><div id='exclamation'>!</div>No comments have been made on this place. Be the first to comment.</a>");
			} else {
				for(i=0; i<=response[0].length-1; i++) {
					$('#comment-box').append("<div class='comment'><span class='user_id'>" + response[0][i]["user_id"] + "</span><div id='comment-photo'><img src='images/" + response[0][i]["user_photo"] + "'></div><div id='vote'><span class='up'>&#x25B2</span><br><span class='vote_count'>" + response[0][i]["votes"] + "</span><br><span class='down'>&#x25BC</span></div><div class='comment-body'><span id='comment-information'><span id='commenter-name'><a href='profile.php?id=" + response[0][i]["user_id"] + "'>" + response[0][i]["username"] + "</a></span><span id='comment-date-time' class='tiny-nl-info'>" + response[0][i]["date_time"] + "</span></span><span class='delete'>&#10006</span><p>" + response[0][i]["body"] + "</p><span class='vote'></span><span class='comment_id'>" + response[0][i]["comment_id"] + "</span></div><div id='clear'></div></div>");
					$('.comment').find('.comment-body').on('mouseenter', function() {
						var comment_user_id = $(this).parent().find('.user_id').text();
						var box = this;
						$.ajax({
							type:'POST',
							url:'check_user_id.php',
							dataType: 'json',
							success: function(response) {
								if(response == comment_user_id) {
									$(box).find('.delete').fadeIn('fast');
								}
						//if response == -1 means user is not logged in
							},
						});
					}).mouseleave(function() {
						$(this).find('.delete').fadeOut('fast');
						$(this).find('.vote').fadeOut('fast');
					});
				}
			}
		},
		complete: function (response) {
			$('#comment-box').slideDown('slow');
			$('#comment-box').fadeIn('slow');
		}
	});
});

$(document).on('click', '#add_new_place',function() {
	$("#drop-down-countries-list").slideUp();
	$("#drop-down-regions-list").slideUp();
	$("#drop-down-places-list").slideUp();
	$("#drop-down-places").slideUp();
	$('#add_new_place').fadeOut(function() {
		$('#add_new_place_form_container').fadeIn();
	});
	//now open up a screen to add new place.
});
	
$(document).on('click', '#cancel-add-new-place', function() {
	$('#add_new_place_form_container').fadeOut();
	$('#add_new_place').fadeIn();
	$("#drop-down-places-list").slideDown();
	$("#drop-down-places").slideDown();
});
	
$(document).on('click', '#place_up_vote',function() {
	var place_id = $('#drop-down-places').find('#final-selection-id').text();
	var vote = parseInt($('#place_vote_count').text());
	var v = 1;
	$.ajax({
		type:'POST',
		url:'submit_place_vote.php',
		data:'id='+place_id+'&vote='+v,
		error: function(request, status, error) {
			 alert(request.responseText);
		},
		success: function(response) {
			if(response == 1) {
				vote = vote + 1;
				$('#place_vote_count').html(vote);
			} else if(response == 3) {
				vote = vote + 2;
				$('#place_vote_count').html(vote);
			} else if(response == 4) {
				error_report("Unknown Error", "Please contact TravelCabin");
			} else {
				error_report("Error Voting", "You already upvoted this.");
			}
		},
		complete: function() {
		},
	});	
});

$(document).on('click', '#place_down_vote',function() {
	var place_id = $('#drop-down-places').find('#final-selection-id').text();
	var vote = parseInt($('#place_vote_count').text());
	var v = -1;
	$.ajax({
		type:'POST',
		url:'submit_place_vote.php',
		data:'id='+place_id+'&vote='+v,
		error: function(request, status, error) {
			 alert(request.responseText);
		},
		success: function(response) {
			if(response == 1) {
				vote = vote - 1;
				$('#place_vote_count').html(vote);
			} else if(response == 3) {
				vote = vote - 2;
				$('#place_vote_count').html(vote);
			} else if(response == 4) {
				error_report("Unknown Error", "Please contact TravelCabin");
			} else {
				error_report("Error Voting", "You already downvoted this.");
			}
		},
		complete: function() {
		},
	});	
});

$(document).on('click', '#profile-photo-click-change',function() {
	$('#overlay').fadeIn().on('click', function() {
		$('#overlay').fadeOut();
		$('#upload-profile-picture-form').fadeOut();
	});
	$('#upload-profile-picture-form').fadeIn();
});

$(document).on('click', '#add-places-photo-button',function() {
	$('#overlay').fadeIn().on('click', function() {
		$('#overlay').fadeOut();
		$('#upload-place-picture-form').fadeOut();
	});
	var place_id = $('#final-selection-id').text();
	$("#place_id_for_photo").val(place_id);
	var place_id = $('#place_id_for_photo').val();
	$('#upload-place-picture-form').fadeIn();
});

$(document).on('click', '#view-all-place-photos-button', function() {
	
});

$(document).on('click','#register-link', function() {
	$('#overlay').fadeIn().on('click', function() {
		$('#overlay').fadeOut();
		$('#register-user-form').fadeOut();
	});
	$('#register-user-form').fadeIn();
});

function register_user(){
	var username = $('#register-user-form #username').val();
	var p1 = $('#register-user-form #password').val();
	var p2 = $('#register-user-form #password2').val();
	$.ajax({
		type:'POST',
		url:'register_user.php',
		data:"username="+username+"&p1="+p1+"&p2="+p2,
		error: function(request, status, error) {
			 alert(request.responseText);
		},
		success:function(response){
			if(response ==0) {
				error_report("Registration Failure", "Username is too Short.");
			} else if (response==1){
				error_report("Registration Failure", "Password is too short");
			} else if(response==2){
				error_report("Registration Failure", "Password mismatch");
			} else if(response == 3) {
				error_report("Registration Failure", "User already exists");
			} else if(response == 4) {
				error_report("Registration Successful", "Congratulations! You may now login and use your account!");
				location.reload();
			}
		},
		complete: function() {
		}
	});
};
$(document).on('click', '.place-photos',function() {
	var src = $(this).attr('src');
	$('#overlay').fadeIn(function() {
		$('#overlay').on('click', function() {
			$('#overlay').fadeOut();
			$('#image-lightbox').empty();
			$('#image-lightbox').fadeOut();
		});
	});
	$('#image-lightbox').fadeIn(function() {
		$('#image-lightbox').on('click', function() {
			$('#overlay').fadeOut();
			$('#image-lightbox').empty();
			$('#image-lightbox').fadeOut();
		});
		$('#image-lightbox').append('<img src="' + src + '">');
	});
});